package com.my.event.publisher;

import cn.hutool.core.io.FastStringWriter;
import com.my.core.domain.log.LogError;
import com.my.core.util.spring.SpringUtil;
import com.my.core.util.WebUtil;
import com.my.event.domin.ErrorLogEvent;
import com.my.event.utils.LogAbstractUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author timo 2021/2/25
 */
public class ErrorLogPublisher {
    public ErrorLogPublisher() {
    }

    public static void publishEvent(Throwable error, String requestUri) {
        HttpServletRequest request = WebUtil.getRequest();
        LogError logError = new LogError();
        logError.setRequestUri(requestUri);
        if (error!=null) {
            FastStringWriter stringWriter = new FastStringWriter();
            error.printStackTrace(new PrintWriter(stringWriter));
            stringWriter.toString();
//            logError.setStackTrace(Exceptions.getStackTraceAsString(error));
            logError.setStackTrace(stringWriter.toString());

            logError.setExceptionName(error.getClass().getName());
            logError.setMessage(error.getMessage());
            StackTraceElement[] elements = error.getStackTrace();
            if (elements!=null) {
                StackTraceElement element = elements[0];
                logError.setMethodName(element.getMethodName());
                logError.setMethodClass(element.getClassName());
                logError.setFileName(element.getFileName());
                logError.setLineNumber(element.getLineNumber());
            }
        }

        LogAbstractUtil.addRequestInfoToLog(request, logError);
        Map<String, Object> event = new HashMap(16);
        event.put("log", logError);
        SpringUtil.publishEvent(new ErrorLogEvent(event));
    }
}
